<template>
    <el-autocomplete v-model="model" :fetch-suggestions="remoteMethod" placeholder="请输入关键词" @select="handleSelect" style="width:100%" :popper-class="textAlign"></el-autocomplete>
</template>

<script>
import { listParentSchoolByName } from 'api/common';

export default {
    props: {
        value: {
            type: [String, Number],
            required: true
        },
        fxSchoolId: {
            type: [String, Number],
            required: true
        }
    },
    computed: {
        model: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val);
            }
        }
    },
    data() {
        return {
            list: null,
            textAlign:'',
            schoolName:''
        }
    },
    created(){
        this.schoolName = this.value;
    },
    methods: {
        remoteMethod(query, cb) {
            if(query ==''){
                cb([{value:'无数据'}]);
                this.textAlign = 'remote-center';
            };
            if(!this.fxSchoolId){
               return
            };
            if(this.schoolName!=query && this.schoolName!=''){
                this.$emit('change','');
            }
            if (query) {
                  listParentSchoolByName(query,this.fxSchoolId).then(response => {
                   this.list = response.data.content;
                   if(this.list==''){
                       this.textAlign = 'remote-center';
                       return;
                   }
                }).then(() => {
                    let results = this.list.filter(this.createStateFilter(query));
                    if(results.length){
                        this.textAlign = '';
                        cb(results)
                    }else{
                        cb([{value:'无数据'}]);
                        this.textAlign = 'remote-center';
                    }
                });
            }  
        },
        createStateFilter(query) {
            return (state) => {
                state.value = state.schoolName; 
                return (state.value.toLowerCase().includes(query.toLowerCase()));
            };
        },
        handleSelect(val) {
            if(val.schoolId){
                this.schoolName = val.schoolName; // 获取缓存学校名字
                this.$emit('change', val.schoolId);
            }else{
                this.$emit('input', '');
            }
        },
    }
}
</script>
